package server.java.autoduel.Locations;

import java.nio.ByteBuffer;

import server.java.autoduel.Network.OPCODES;
import server.java.autoduel.Network.Util;

import com.sun.sgs.app.AppContext;

/**
 * Represents a TruckStop location
 * 
 * @author Ian Axelrod
 * @author Liz Ha
 * @author Andrew Muldowney
 * @author Edward Futch
 */
public class TruckStop extends Location {
	private static final long serialVersionUID = 5381893855196294660L;

	/**
	 * The rumors associated with this truckstop
	 */
	private String[] rumors;

	/**
	 * Chasses available at this truckstop
	 */
	// private ArrayList<ManagedReference<Chassis>> chasses = new
	// ArrayList<ManagedReference<Chassis>>();

	@Override
	public ByteBuffer encodePacket(OPCODES opcode) {
		switch (opcode) {
		case ORD_UPDLOC: {
			int rumorsSize = 0;

			for (final String rumor : this.rumors) {
				rumorsSize += rumor.length() + 1;
			}

			final byte[] bytes = new byte[1 + // opcode
					TruckStop.class.getSimpleName().length() + 1 + // delim
					this.name.length() + 1 + // delim
					4 + // storage for count of rumors
					rumorsSize + // storage for rumors themselves
					4 + // coord.X
					4 + // coord.Y
					1]; // delim
			final ByteBuffer buf = ByteBuffer.wrap(bytes);

			buf.put((byte) OPCODES.ORD_UPDLOC.ordinal());
			buf.put(TruckStop.class.getSimpleName().getBytes());
			buf.put(Util.PKT_DLM);
			buf.put(this.name.getBytes());
			buf.put(Util.PKT_DLM);
			buf.putInt(this.rumors.length);
			for (final String rumor : this.rumors) {
				buf.put(rumor.getBytes());
				buf.put(Util.PKT_DLM);
			}
			buf.putInt(this.coords.x);
			buf.putInt(this.coords.y);
			buf.put(Util.PKT_DLM);
			buf.flip();

			return buf;
		}
		default: {
			return null;
		}
		}
	}

	/**
	 * @return the rumors
	 */
	public String[] getRumors() {
		return this.rumors;
	}

	/**
	 * @param chasses
	 *            the chasses to set
	 */
	/*
	 * public void setChasses(ArrayList<Chassis> chasses) { DataManager
	 * dataManager = AppContext.getDataManager();
	 * 
	 * dataManager.markForUpdate(this); this.chasses.clear(); for (Chassis
	 * chassis : chasses) {
	 * this.chasses.add(dataManager.createReference(chassis)); } }
	 */

	@Override
	public void loadMembers() {
		// setChasses(ChassisFactory.provideChasses());
	}

	/**
	 * @return the chasses
	 */
	/*
	 * public ArrayList<Chassis> getChasses() { ArrayList<Chassis> tmpChasses =
	 * new ArrayList<Chassis>();
	 * 
	 * for (ManagedReference<Chassis> chassisRef : chasses) {
	 * tmpChasses.add(chassisRef.get()); }
	 * 
	 * return tmpChasses; }
	 */

	/**
	 * @param rumors
	 *            the rumors to set
	 */
	public void setRumors(String[] rumors) {
		AppContext.getDataManager().markForUpdate(this);
		this.rumors = rumors;
	}
}